package dm.api;

import java.util.Iterator;

import dm.api.filter.ViewFilter;
import dm.bsi.Deployment;
import dm.bsi.Log;
import dm.bsi.LogNode;
import dm.bsi.Node;
import indi.zjh.dp.access.Api;
import indi.zjh.dp.access.ApiContext;
import indi.zjh.dp.db.Configuration;
import indi.zjh.dp.db.Session;
import indi.zjh.dp.orm.Query;
import indi.zjh.dp.orm.Result;
import indi.zjh.dp.verify.CharSetRule;
import indi.zjh.dp.verify.Check;
import indi.zjh.dp.verify.ValueRangeRule;

public class GetLogApi extends Api {

	private static final int NODE = 0;
	private static final int DEPLOYMENT = 1;
	@Override
	public void process(ApiContext ctx) throws Exception {
		// TODO Auto-generated method stub
		Session session = Configuration.getSessionFactory().createSession();
		try 
		{
			ViewFilter viewFilter = new ViewFilter(ctx);
			viewFilter.preprocess();
			
			String name = ctx.getRequestParamValue("name");
			String nStr = ctx.getRequestParamValue("n");
			
			Check.data(name).desc("请输入合法存在的工作节点名称").rule(new CharSetRule(CharSetRule.NAME_SET));
			
			int nLog = 32;
			if(nStr != null && !nStr.isEmpty())
			{
				Check.data(nStr).desc("请输入合法的日志记录数, 取值范围: 1 - 512").rule(new ValueRangeRule(1, 512));
				nLog = Integer.parseInt(nStr);
			}
			
			int type = NODE;
			LogNode node = null;
			Log[] logs = null;
			Query<Node> nodeQuery = new Query<Node>(session);
			Result<Node> nodeResult = nodeQuery.find(Node.class, "`name` = '"+name+"'").result();
			if(nodeResult.count() == 0)
			{
				type = DEPLOYMENT;
				Query<Deployment> deploymentQuery = new Query<Deployment>(session);
				Result<Deployment> deploymentResult = deploymentQuery.find(Deployment.class, "`name` = '"+name+"'").result();
				if(deploymentResult.count() == 0)
				{
					throw new Exception("没有找到关于 "+name+" 的日志");
				}
				node = deploymentResult.iterator().next();
				logs = Log.getLog(session, node, nLog);
			}
			else
			{
				node = nodeResult.iterator().next();
				logs = Log.getLog(session, node, nLog);
			}
			
			if(type == NODE)
			{
				viewFilter.writeResponse("#####  工作节点["+name+"]日志  #####");
			}
			else
			{
				viewFilter.writeResponse("##### 部署["+name+"]");
			}
			
			for(int i = 0; i < logs.length; ++i)
			{
				viewFilter.writeResponse(logs[i].getCreated()+":"+logs[i].getContent());
			}
			viewFilter.writeResponse("OK");
		}
		catch (Exception e) 
		{
			// TODO: handle exception
			ctx.writeResponse("FAIL:"+e.getMessage());
			session.rollback();
			e.printStackTrace();
		}
		finally {
			session.close();
		}
	}

}
